<template>
	<view>
		<!-- 活动轮播图 -->
		<uni-swiper-dot class="uni-list-cell-db" :info="new Array(carouselImage.length)" :current="current"
			mode="round">
			<swiper autoplay class="swiper-box" :current="swiperDotIndex" @change="change">
				<swiper-item v-for="(item, index) in carouselImage" :key="index">
					<view class="swiper-item">
						<image mode="widthFix" style="width: 100%"
							:src="organizationGateway + '/file/download?filepath=' + item?.image?.mmUrl" class="img">
						</image>
					</view>
				</swiper-item>
			</swiper>
		</uni-swiper-dot>

		<view class="detail-title">
			<view style="flex: 1; display: flex; margin-top: 4px">
				<view style="color: #fff; font-weight: 400">
					￥{{ numberFormat(commodity?.ocPric || 0, 0) + "/1" + commodity?.info?.ciUnit }}
				</view>
				<view style="color: #fff; text-decoration: line-through; margin: 3px 10px 0 10px; font-size: 12px">
					￥{{ numberFormat(commodity?.info?.ciMava || 0, 0) + "/1" + commodity?.info?.ciUnit }}</view>
			</view>
			<view style="display: flex; margin-top: 7px; font-size: 13px; color: #fff">
				<view> {{ commodity?.ocSaqu || 0 }} 人购买 </view>
				<view style="margin: 0 10px"> | </view>
				<view>
					仅剩
					{{ Number(commodity?.ocQuat) || 0 }}
					件
				</view>
			</view>
		</view>

		<view class="mb-title">{{ commodity?.info?.ciAlna }}</view>

		<uni-card :is-shadow="false" is-full padding="15px 0">
			<view style="position: relative">
				{{ commodity?.info?.ciDesc || 0 }}
			</view>
		</uni-card>

		<view style="margin-bottom: 5px"></view>

		<!-- <uni-section v-if="activityItemStores?.filter((item) => activityStores?.findIndex((_item) => item.osUuid === _item.osUuid) !== -1).length > 0" title="适用门店" type="line" padding="0">
            <uni-list>
                <uni-list-item v-for="(item, index) in activityItemStores?.filter((item) => activityStores?.findIndex((_item) => item.osUuid === _item.osUuid) !== -1)">
                    <template v-slot:header>
                        <uni-badge :text="index + 1" type="primary" size="normal" />
                    </template>
                    <template v-slot:body>
                        <view class="slot-text">
                            <view style="font-size: 14px; margin-left: 5px">{{ item.osName }}</view>
                            <view style="font-size: 12px; margin-left: 5px; color: #a1a3a6; width: 220px">
                                {{ item.osZoad + "/" + item.osDead }}
                            </view>
                        </view>
                    </template>
                    <template v-slot:footer>
                        <view style="display: flex">
                            <view style="font-size: 12px; text-align: right; width: 30px" @click="phoneCall(item.osPhon)">
                                <uni-icons type="phone" size="24"></uni-icons>
                            </view>
                            <view style="font-size: 12px; text-align: right; width: 30px" @click="mapLocation(Number(item.osCoox), Number(item.osCooy))">
                                <uni-icons type="location" size="24"></uni-icons>
                            </view>
                        </view>
                    </template>
                </uni-list-item>
            </uni-list>
        </uni-section> -->

		<view>
			<image v-for="(item, index) in detailImage" mode="widthFix" style="width: 100%"
				:src="organizationGateway + '/file/download?filepath=' + item.image.mmUrl"></image>
		</view>

		<uni-section v-if="noticeItem.nsName" title="注意事项" type="line" padding="0">
			<uni-list>
				<uni-list-item v-for="(item, index) in noticeItem.detail">
					<template v-slot:header>
						<uni-badge :text="index + 1" type="warning" size="normal" />
					</template>
					<template v-slot:body>
						<view class="slot-text">
							<view style="font-size: 14px; margin-left: 5px">{{ item?.ndDesc }} </view>
						</view>
					</template>
				</uni-list-item>
			</uni-list>
		</uni-section>

		<view class="actions">
			<view class="item menu" @click="goHome">
				<uni-icons type="home" size="24"></uni-icons>
				<view>首页</view>
			</view>
			<view class="item menu" @click="goCart">
				<uni-icons type="cart" size="24"></uni-icons>
				<uni-badge :text="cartTotal" class="ac-badge" v-if="cartTotal > 0" />
				<view>购物车</view>
			</view>
			<view class="item menu" @click="openShareShow()">
				<uni-icons type="redo" size="24"></uni-icons>
				<view>分享</view>
			</view>

			<view>
				<view style="flex: 1; display: flex; padding-top: 4px">
					<view style="flex: 1; margin-left: 3px; width: 120px">
						<u-button type="error" text="加入购物车"
							color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"
							@click="authorization('cart')">
						</u-button>
					</view>
					<view style="flex: 1; margin-left: 3px; width: 120px">
						<u-button type="warning" text="直接购买" @click="authorization('buy')"> </u-button>
					</view>
				</view>
			</view>
		</view>

		<uni-popup ref="popup_share" background-color="#fff">
			<view style="text-align: center; color: #4f5555; margin: 15px 0">分享到</view>
			<view class="share-button" style="display: flex; justify-content: space-between; align-items: center">
				<view style="text-align: center; padding: 10px 0 10px 60px">
					<button open-type="share" hover-class="none" style="text-align: center">
						<image class="share-icon" src="../../static/icons/wechat.png"></image>
					</button>
					<view style="margin-bottom: 10px">分享给好友</view>
				</view>

				<view style="text-align: center; margin: 0 60px 10px 0" @click="handlePoster()">
					<image class="share-icon" src="../../static/icons/friend.png"></image>
					<view>分享到朋友圈</view>
				</view>
			</view>
		</uni-popup>

		<view>
			<u-modal :show="isOpened" confirmText="保存到相册" cancelText="关闭显示" showCancelButton="true" width="350px"
				@confirm="saveImg()" @cancel="colsePos()">
				<canvas style="width: 310px; height: 430px" canvas-id="myCanvas"></canvas>
			</u-modal>
		</view>

		<!-- 授权微信手机号弹窗 -->
		<uni-popup ref="popup_phone" background-color="#fff">
			<view style="padding: 30px">
				<button type="primary" open-type="getPhoneNumber"
					@getphonenumber="(e) => decryptPhoneNumber(e, $store, $refs, appid, activity)">
					微信一键授权
				</button>
			</view>
		</uni-popup>

		<!-- 下单 -->
		<!-- 		<uni-popup ref="popup_order" background-color="#fff">
			<order-popup :activityItem="activityItem" :appointment="appoint" :orderType="orderType"
				:closePopup="closePopup" :callback="submitOrderCallback" />
		</uni-popup> -->

		<!-- 购买确认数量弹层 -->
		<uni-popup ref="popup_quantity_confirm" background-color="#fff">
			<view class="goods-popup bg-white pr" style="padding: 20rpx;">
				<!-- 规格基础信息 -->
				<view class="goods-popup-base oh br-b pr">
					<image
						:src="this.commodity?.info?.ciPict ? organizationGateway + '/file/download?filepath=' + this.commodity?.info?.ciPict[0]?.path : ''"
						mode="scaleToFill" class="radius br"></image>
					<view class="goods-popup-base-content">
						<view class="goods-price">
							<view class="sales-price">{{"￥" + numberFormat(this.commodity?.ocPric, 2)}}</view>
							<view class="original-price">{{"￥" + numberFormat(this.commodity?.info?.ciMava, 2)}}</view>
						</view>
						<view class="inventory">
							<text class="cr-gray">库存</text>
							<text class="cr-base">{{numberFormat(this.commodity?.ocQuat, 0)}}</text>
							<text class="cr-gray">{{this.commodity?.info?.ciUnit}}</text>
						</view>
					</view>
				</view>

				<view class="goods-popup-content">
					<!-- 购买数量 -->
					<view class="goods-buy-number oh">
						<view class="title fl">购买数量</view>
						<view class="number-content oh round" style="text-align: center;">
							<view @tap="goods_buy_number_event" class="number-submit cr-gray fl" data-type="0"
								style="text-align: center;">-
							</view>
							<input @blur="goods_buy_number_blur" class="cr-gray fl" type="number" :value="buy_number"
								style="text-align: center;">
							<view @tap="goods_buy_number_event" class="number-submit cr-gray fl" data-type="1"
								style="text-align: center;">+
							</view>
						</view>
					</view>
				</view>
				<button class="goods-popup-submit bg-main cr-white" type="default" @tap.stop="goods_buy_confirm_event"
					hover-class="none">确定</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex";

	import {
		getWxCode,
		getWxPhoneNumber,
		getCustomerByCiPhon,
		createCustomers,
		createPlatformConsumerInfo,
		createCustomerLoginRelationship,
		updateCustomerByCiUuid,
		mergeGuestToCustomer,
		loadCommodityByCiUuid,
		createItemAppointment,
		getCustOrderBySoCuidAndSoItem,
		createActivityItemSpellOrder,
	} from "../../utils/api.js";
	import {
		numberFormat,
		userAuthorization,
		saveShareRecord,
		pageBrowseStart,
		pageBrowseEnd,
		UTCTimeToLocal,
	} from "../../utils/helper";

	export default {
		data() {
			return {
				isOpened: false,
				posterImg: "",
				isBrowse: false,
				pageUserInfo: {},
				current: 0,
				authInfo: "",
				commodity: {},
				detailImage: [],
				carouselImage: [],
				ciUuid: "",
				noticeItem: {},
				cartTotal: 0,
				buy_number: 1,
				buy_event_type: ""
			};
		},

		async onLoad(params) {
			this.ciUuid = params.ciUuid || "";
			if (params.isJump) {
				this.$store.dispatch("personInfo/saveParams", {
					staffId: params.staffId || "",
					shareId: params.shareId || "",
				});
			}
			if (params.ciUuid && this.orUuid) {
				let res = await loadCommodityByCiUuid(params.ciUuid, this.orUuid);
				this.commodity = res?.commodity || {};
				this.noticeItem = res?.noticeItem || {};
				this.detailImage = res?.detail || [];
				this.carouselImage = res?.carousel || [];
			}

			wx.showShareMenu({
				withShareTicket: true,
				menus: ["shareAppMessage", "shareTimeline"],
			});

			// let userInfo = uni.getStorageSync("userInfo");
			// if (userInfo?.openId && params.isJump === "yes" && userInfo?.isLogin === true) {
			//     let rlData = {
			//         gpUuid: this.gpUuid,
			//         ciUuid: userInfo.ciUuid,
			//         clTime: new Date().getUTCTime(),
			//     };
			//     if (params.shareId) rlData.scUuid = params.shareId;
			//     if (params.staffId) rlData.orUuid = params.staffId;
			//     if (params.shareId || params.staffId) {
			//         createCustomerLoginRelationship(rlData);
			//     }
			// }
		},

		onHide() {
			pageBrowseEnd(this.pageUserInfo.gbUuid, this.pageUserInfo.gbInti);
			this.isBrowse === false;
		},

		computed: {
			...mapGetters({
				appid: "globalInfo/appid",
				merchantStores: "globalInfo/merchantStores",
				organizationGateway: "globalInfo/organizationGateway",
				globalUserInfo: "personInfo/userInfo",
				defaultImageBase64: "globalInfo/defaultImageBase64",
				orUuid: "dailyInfo/orUuid",
				cartInfo: "dailyInfo/cartInfo",
			}),
		},

		watch: {
			orUuid: {
				async handler(newValue, oldValue) {
					if (newValue && this.ciUuid) {
						let res = await loadCommodityByCiUuid(this.ciUuid, newValue);
						this.commodity = res?.commodity || {};
						this.noticeItem = res?.noticeItem || {};
						this.detailImage = res?.detail || [];
						this.carouselImage = res?.carousel || [];
					}
				},
				immediate: true,
				deep: true,
			},
			cartInfo: {
				handler(newValue, oldValue) {
					if (newValue) {
						let cartTotal = 0
						newValue.map(item => cartTotal += item.count)
						this.cartTotal = cartTotal
					}
				},
				immediate: true,
				deep: true,
			},
		},

		// 转发
		onShareAppMessage(res) {
			// let gpUuid = this.activity?.gpUuid || "";
			// let giUuid = this.activityItem?.giUuid || "";
			// const { staffId, shUuid } = saveShareRecord(gpUuid);
			let ciUuid = this.ciUuid;
			return {
				title: this.commodity?.info?.ciAlna,
				path: `/pages/daily/commodity_detail?isJump=yes&ciUuid=${ciUuid}&shareId=${shUuid}&staffId=${staffId}`,
				imageUrl: this.organizationGateway + "/file/download?filepath=" + this.carouselImage[0].image.mmUrl,
			};
		},

		// 朋友圈
		onShareTimeline(res) {
			// let gpUuid = this.activity?.gpUuid || "";
			// let giUuid = this.activityItem?.giUuid || "";
			// const { staffId, shUuid } = saveShareRecord(gpUuid);
			let ciUuid = this.ciUuid;
			return {
				title: this.commodity?.info?.ciAlna,
				imageUrl: this.organizationGateway + "/file/download?filepath=" + this.carouselImage[0].image.mmUrl,
				query: `isJump=yes&ciUuid=${ciUuid}&shareId=${shUuid}&staffId=${staffId}`,
			};
		},

		methods: {
			phoneCall(phone) {
				uni.makePhoneCall({
					phoneNumber: phone,
				});
			},

			change(e) {
				this.current = e.detail.current;
			},

			mapLocation(osCoox, osCooy) {
				uni.openLocation({
					latitude: osCoox,
					longitude: osCooy,
				});
			},

			openShareShow() {
				this.$refs.popup_share.open("bottom");
			},

			goHome() {
				uni.switchTab({
					url: "/pages/home/index",
				});
			},

			goCart() {
				uni.switchTab({
					url: "/pages/cart/cart",
				});
			},

			async getWxCode() {
				const fs = uni.getFileSystemManager();
				const filePath = `${wx.env.USER_DATA_PATH}/${this.commodity.ciUuid}.png`;
				try {
					fs.accessSync(filePath);
				} catch (e) {
					let pages = getCurrentPages();
					let currPage = pages[pages.length - 1];
					let userInfo = uni.getStorageSync("userInfo") || "";
					let staffId = uni.getStorageSync("staffId") || ""; // 员工Id
					let shUuid = userInfo?.ciUuid || "";
					let res = await getWxCode({
						appid: this.appid,
						page: currPage.route,
						scene: this.commodity.ciUuid,
					});
					if (res) {
						// 将返回的图片buffer生成图片，并保存至临时用户文件中
						fs.writeFileSync(filePath, res, "base64");
					}
				}
				return filePath;
			},

			handlePoster() {
				let userInfo = uni.getStorageSync("userInfo");
				let nickName = userInfo.nickName;
				let itemImage =
					this.commodity?.info?.ciPict?.length > 0 ?
					this.organizationGateway + "/file/download?filepath=" + this.commodity?.info?.ciPict[0].path :
					defaultImageBase64;
				this.$refs.popup_share.close();
				uni.showLoading({
					title: "海报生成中",
					mask: true,
				});
				uni.downloadFile({
					url: itemImage,
					success: (res) => {
						let bgImg = res.tempFilePath;
						uni.downloadFile({
							url: userInfo.avatarUrl,
							success: async (res1) => {
								let codeImg = await this.getWxCode();
								let avatar = res1.tempFilePath;
								await this.drawPoster(bgImg, avatar, codeImg, nickName);
								uni.hideLoading();
							},
						});
					},
				});
			},

			drawPoster(bgImg, avatar, codeImg, nickName) {
				let _this = this;
				_this.isOpened = true;
				let ctx = uni.createCanvasContext("myCanvas", _this);
				// 绘制背景
				ctx.setFillStyle("#f58220");
				ctx.fillRect(10, 10, 290, 410);

				// 绘制头像
				ctx.save();
				ctx.beginPath();
				ctx.arc(40 / 2 + 25, 40 / 2 + 25, 40 / 2, 0, Math.PI * 2, false);
				ctx.clip();
				ctx.drawImage(avatar, 25, 25, 40, 40);
				ctx.restore();

				//绘制名称
				ctx.setFontSize(14);
				ctx.setFillStyle("#fffffb");
				ctx.fillText(nickName, 70, 40);
				ctx.setFontSize(12);
				ctx.fillText("超级惊喜，不期而遇", 70, 58);

				//绘制中央区域
				ctx.save();
				ctx.setFillStyle("#fffffb");
				ctx.setLineJoin("round"); //交点设置成圆角
				ctx.setLineWidth(16);
				ctx.setStrokeStyle("#fffffb");
				ctx.strokeRect(30, 80, 250, 320);
				ctx.fillRect(35, 75, 250, 320);
				ctx.closePath();
				ctx.restore();

				// 绘制中央区域图片
				ctx.drawImage(bgImg, 30, 80, 250, 230);

				// 绘制价格
				ctx.setFontSize(12);
				ctx.setFillStyle("#999d9c");
				ctx.fillText(`原价：${_this.activityItem?.giInpr}`, 30, 350);
				ctx.beginPath();
				ctx.rect(30, 345, 82, 2);
				ctx.fill();

				ctx.font = "normal bold 20px 宋体";
				ctx.setFillStyle("red");
				ctx.fillText(`￥${_this.activityItem?.giGppr}`, 30, 333);

				// 绘制项目名称
				ctx.setFillStyle("#130c0e");
				ctx.font = "normal normal 14px 宋体";
				const str = _this.activityItem?.giName;
				_this.toFormateStr(ctx, str, 135, 2, 32, 374, 21);

				// 绘制小程序码
				ctx.drawImage(codeImg, 200, 325, 65, 65);
				ctx.draw();
				//将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
				setTimeout(function() {
					uni.canvasToTempFilePath({
						canvasId: "myCanvas",
						success: function(res) {
							let tempFilePath = res.tempFilePath;
							_this.posterImg = tempFilePath;
						},
						fail: function(res) {
							console.log(res);
						},
					});
				}, 200);
			},

			toFormateStr(ctx, str, draw_width, lineNum, startX, startY, steps) {
				let drawWidth = ctx.measureText(str).width;
				let strLN = drawWidth / draw_width;
				let drawLine = Math.ceil(strLN); //行数
				let strLen = parseInt(str.length / strLN); //每行字数
				let startPoint = startY;

				if (drawWidth < draw_width) {
					ctx.fillText(str, startX, startY);
				} else {
					for (let i = 0; i < drawLine; i++) {
						let startStr = strLen * i;
						if (i + 1 < lineNum) {
							ctx.fillText(str.substring(startStr, startStr + strLen), startX, startPoint);
						}
						if (i + 1 == lineNum) {
							ctx.fillText(str.substring(startStr, startStr + strLen), startX, startPoint);
						}
						startPoint += steps;
					}
				}
			},

			saveImg() {
				uni.saveImageToPhotosAlbum({
					filePath: this.posterImg,
					success: (res) => {
						uni.showToast({
							title: "已保存到相册",
							icon: "success",
							duration: 3000,
						});
					},
					fail: async (err) => {
						if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
							const ret = await uni.getSetting();
							if (ret.authSetting["scope.writePhotosAlbum"]) {
								uni.showToast({
									title: "已授权",
									icon: "success",
								});
							}
							if (ret.authSetting["scope.writePhotosAlbum"] == false) {
								uni.showModal({
									title: "提示",
									content: "图片保存失败，请前往设置页面允许保存相册",
									confirmColor: "#8C5CDD",
									success: function(res) {
										if (res.confirm) {
											uni.openSetting({
												success(res) {
													console.log(res);
												},
											});
										}
										if (res.cancel) {
											uni.showToast({
												title: "取消",
												icon: "error",
											});
										}
									},
								});
							}
						}
					},
				});
			},

			colsePos() {
				this.isOpened = false;
			},

			async authorization(item) {
				if (item === "buy") {
					this.buy_event_type = "直接购买";
					this.$refs.popup_quantity_confirm.open("bottom");
				}
				if (item === "cart") {
					this.buy_event_type = "加购物车";
					this.$refs.popup_quantity_confirm.open("bottom");
				}

				// this.authInfo = item;
				// let userInfo = uni.getStorageSync("userInfo");

				// if (userInfo?.openId) {
				//     if (userInfo.phone) {
				//         if (item === "alone") {
				//             this.orderType = "单独购买";
				//             this.onAlonePurchase();
				//         }
				//     } else {
				//         this.$refs.popup_phone.open("bottom");
				//     }
				// } else {
				//     let user = await userAuthorization(this.activity.gpUuid);
				//     if (user) {
				//         this.$store.dispatch("personInfo/save", {
				//             userInfo: user,
				//         });
				//         if (user?.phone) {
				//             if (item === "alone") {
				//                 this.orderType = "单独购买";
				//                 this.onAlonePurchase();
				//             }
				//         } else this.$refs.popup_phone.open("bottom");
				//     }
				// }
			},

			goods_buy_number_event(e) {
				let type = parseInt(e.currentTarget.dataset.type) || 0;
				let temp_number = parseInt(this.buy_number);
				let number = (type == 0) ? temp_number - 1 : temp_number + 1;
				if (number > 0) {
					this.buy_number = number
				} else {
					uni.showToast({
						title: "起购数为1",
						icon: "error",
						duration: 3000,
					});
					return
				}
			},

			goods_buy_number_blur(e) {
				let number = parseInt(e.detail.value) || 1;
				if (isNaN(number)) {
					number = 1;
				}
				this.buy_number = number
			},

			goods_buy_confirm_event(e) {
				switch (this.buy_event_type) {
					case '直接购买':
						let data = {
							"buy_type": "commodity",
							"ciUuid": this.commodity?.ciUuid,
							"count": this.buy_number,
						};
						uni.navigateTo({
							url: '/pages/buy/buy?data=' + JSON.stringify(data)
						});
						this.$refs.popup_quantity_confirm.close();
						break;
					case '加购物车':
						let cartInfo = this.cartInfo
						if (cartInfo?.length > 0) {
							let step = true
							for (let i = 0; i < cartInfo?.length; i++) {
								let item = cartInfo[i]
								if (item?.ciUuid && this.commodity?.ciUuid && item.ciUuid === this.commodity?.ciUuid) {
									item.count = item.count + this.buy_number
									step = false
								}
							}
							if (step) {
								if (this.commodity?.ciUuid) {
									cartInfo.push({
										ciUuid: this.commodity.ciUuid,
										count: this.buy_number,
										selected: false
									})
								}
							}
						} else {
							if (this.commodity?.ciUuid) {
								cartInfo.push({
									ciUuid: this.commodity.ciUuid,
									count: this.buy_number,
									selected: false
								})
							}
						}
						this.$store.dispatch("dailyInfo/save_cart", {
							cartInfo,
						});
						uni.showToast({
							title: "添加成功",
							icon: "success",
							duration: 3000,
						});
						this.$refs.popup_quantity_confirm.close();
						break;
				}
			},

			async decryptPhoneNumber(e, $store, $refs, appid, activity) {
				$refs.popup_phone.close();
				if (e.detail.errMsg !== "getPhoneNumber:ok") return;

				let userInfo = uni.getStorageSync("userInfo"); // 用户信息

				let brwseData = {
					ciUuid: userInfo.ciUuid,
				};

				const phoneInfo = await getWxPhoneNumber({
					appid,
					...e.detail,
				});
				if (!phoneInfo?.phone_info?.phoneNumber)
					return uni.showToast({
						title: "没获取到手机号",
						icon: "error",
						duration: 2000,
					});

				let resCust = await getCustomerByCiPhon({
					ciPhon: phoneInfo.phone_info.phoneNumber,
				});
				let shareId = uni.getStorageSync("shareId") || ""; // 分享人ID
				let staffId = uni.getStorageSync("staffId") || ""; // 员工ID

				if (!resCust?.ciUuid) {
					let data = {
						ciPhon: phoneInfo.phone_info.phoneNumber,
						ciAvat: userInfo.avatarUrl,
						ciFrom: "新客",
						ciCity: userInfo.city,
						ciPrin: userInfo.province,
						ciAlia: userInfo.nickName,
						openId: userInfo.openId,
						appId: appid,
						orUuid: staffId || null,
					};
					let resId = await createCustomers(data);

					if (resId) {
						userInfo.ciUuid = resId?.ciUuid;
						userInfo.phone = phoneInfo.phone_info.phoneNumber;
						userInfo.isNew = true;
						userInfo.isLogin = true;

						$store.dispatch("personInfo/save", {
							userInfo,
						});

						createPlatformConsumerInfo({
							ciAlia: userInfo.nickName,
							ciAvat: userInfo.avatarUrl,
							ciPhon: userInfo.phone,
							appId: appid,
							openId: userInfo.openId,
						});

						let rlData = {
							gpUuid: activity.gpUuid,
							ciUuid: userInfo.ciUuid,
							clTime: new Date().getUTCTime(),
						};

						if (shareId) rlData.scUuid = shareId;
						if (staffId) rlData.orUuid = staffId;

						if (staffId || shareId) {
							createCustomerLoginRelationship(rlData);
						}
					}
				} else {
					let data = {
						ciUuid: resCust?.ciUuid,
						ciPhon: phoneInfo.phone_info.phoneNumber,
						ciAvat: userInfo.avatarUrl,
						ciCity: userInfo.city,
						ciPrin: userInfo.province,
						ciAlia: userInfo.nickName,
						openId: userInfo.openId,
						appId: appid,
					};

					let res1 = await updateCustomerByCiUuid(data);

					if (res1) {
						userInfo.ciUuid = resCust?.ciUuid;
						userInfo.phone = phoneInfo.phone_info.phoneNumber;
						userInfo.isNew = resCust?.ciFrom === "新客" ? true : false;
						userInfo.ciName = resCust?.ciName;
						userInfo.isLogin = true;

						$store.dispatch("personInfo/save", {
							userInfo,
						});

						createPlatformConsumerInfo({
							ciAlia: userInfo.nickName,
							ciAvat: userInfo.avatarUrl,
							ciPhon: userInfo.phone,
							appId: appid,
							openId: userInfo.openId,
						});

						let rlData = {
							gpUuid: activity.gpUuid,
							ciUuid: userInfo.ciUuid,
							clTime: new Date().getUTCTime(),
						};
						if (shareId) rlData.scUuid = shareId;
						if (staffId) rlData.orUuid = staffId;
						if (staffId || shareId) {
							createCustomerLoginRelationship(rlData);
						}
					}
				}

				brwseData.ciUuidNew = userInfo.ciUuid;
				brwseData.ciAlia = userInfo.nickName;
				brwseData.ciType = userInfo.isNew ? "新客" : "老客";

				mergeGuestToCustomer(brwseData);

				if (this.authInfo === "alone") {
					this.orderType = "单独购买";
					this.onAlonePurchase();
				}
			},

			onAlonePurchase() {
				this.handlePlaceOrder();
			},
			// 订单限购
			async handlePlaceOrder() {
				let userInfo = uni.getStorageSync("userInfo"); // 用户信息
				let count = 0;

				let res = await getCustOrderBySoCuidAndSoItem({
					soCuid: userInfo?.ciUuid,
					soItem: this.commodity?.ciUuid,
				});
				if (res.totalCount < count) {
					this.$refs.popup_order.open("bottom");
				} else {
					if (res?.nodes?.findIndex((item) => item.soStat === "待支付") !== -1) {
						uni.navigateTo({
							url: `/pages/my/orders`
						});
					} else uni.showToast({
						title: "您已超过限购次数",
						icon: "error",
						duration: 2000
					});
				}
			},

			async submitOrderCallback(data) {
				if (!data?.soUuid) return uni.showToast({
					title: "没有订单信息",
					icon: "error"
				});
				if (data.soType === "单独购买" || data.soType === "新团订单") {
					let spRes = await createActivityItemSpellOrder({
						soUuid: data.soUuid
					});
					if (spRes) {
						this.$refs.popup_order.close();
						uni.showToast({
							title: "支付成功",
							icon: "success",
						});
						if (spRes.ggUuid) {
							uni.navigateTo({
								url: `/pages/activities/spell_order_detail?ggUuid=${spRes.ggUuid}&gpUuid=${this.activityItem?.gpUuid}&giUuid=${this.activityItem.giUuid}`,
							});
						} else {
							uni.redirectTo({
								url: `/pages/my/orders?giUuid=${this.activityItem.giUuid}&gpUuid=${this.activityItem?.gpUuid}`,
							});
						}
					}
				}
			},

			closePopup() {
				this.$refs.popup_order.close();
			},
		},
	};
</script>

<style>
	page {
		padding-bottom: 55px;
		background-color: #eee;
	}
</style>

<style lang="scss" scoped>
	page {
		padding-bottom: 55px;
		background-color: #eee;
	}

	.share-button button {
		background-color: #fff;
		height: 45px;
	}

	.share-button button::after {
		border: none;
	}

	.slot-text {
		flex: 1;
		font-size: 14px;
		margin-right: 10px;
	}

	.swiper-box {
		width: 100%;
		height: 240px;
	}

	.swiper-box .img {
		width: 100%;
		background-size: cover;
	}

	.detail-title {
		display: flex;
		background-color: #c1a173;
		height: 30px;
		margin-top: -10px;
		padding: 10px 20px;
	}

	.mb-title {
		font-weight: 800px;
		font-size: 16px;
		padding: 10px 0 10px 10px;
		background-color: #fff;
	}

	.detail-share-btn {
		position: absolute;
		right: -6px;
		top: -4px;
		background-color: #c1a173;
		color: #fff;
		border-radius: 20px 0 0 20px;
		margin-right: -13px;
		padding: 5px 5px 5px 5px;
		font-size: 12px;
		width: 60px;
		text-align: center;
	}

	.store-title {
		margin-top: 5px;
		font-weight: 800px;
		font-size: 12px;
		padding: 5px 0 5px 10px;
		background-color: #fff;
	}

	.collate-title {
		margin-top: 5px;
		font-weight: 800px;
		font-size: 14px;
		padding: 10px 0 10px 10px;
		background-color: #fff;
		display: flex;
		justify-content: space-between;
	}

	.actions {
		width: 100%;
		position: fixed;
		bottom: 0;
		height: 50px;
		border-top: 1px solid #eee;
		background-color: #fff;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.actions .item {
		text-align: center;
		font-size: 11px;
	}

	.actions .menu {
		width: 100px;
	}

	.actions .ac-badge {
		position: absolute;
		left: 70px;
	}

	.actions .bnts {
		display: flex;
	}

	.share-icon {
		width: 40px;
		height: 40px;
	}

	/**
	 * 弹窗基础
	 */
	.goods-popup-base {
		height: 230rpx;
	}

	.goods-popup-base image {
		width: 200rpx;
		height: 200rpx;
		position: absolute;
		left: 0;
		top: 0;
	}

	.goods-popup-base-content {
		position: absolute;
		left: 220rpx;
		top: 0;
	}

	.goods-popup-base-content .goods-price {
		margin-bottom: 10rpx;
	}

	.goods-popup-content {
		max-height: 50vh;
		overflow-y: scroll;
		overflow-x: hidden;
		margin-top: 20rpx;
	}

	.goods-buy-number {
		margin-bottom: 20rpx;
		position: relative;
		height: 70rpx;
	}

	.goods-buy-number .title {
		line-height: 60rpx;
	}

	.goods-popup .number-content {
		position: absolute;
		right: 20rpx;
		top: 0;
		background: #eee;
		border-radius: 2px;
		border: 1px solid #eee;
	}

	.goods-popup .number-content .number-submit {
		width: 80rpx;
		font-weight: bold;
	}

	.goods-popup .number-content input {
		width: 50px;
		background: #fff;
		border-radius: 0px;
	}

	.goods-popup .number-content .number-submit,
	.goods-popup .number-content input {
		padding: 0;
		vertical-align: middle;
		height: 60rpx;
		line-height: 60rpx;
	}
</style>
